package ai.iyoga.dao;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;

import ai.iyoga.been.Card;
import ai.iyoga.util.TransactionManager;

public class CardDao {

	public void addCard(Card card) {
		try {
			String sql = "INSERT INTO card (CARD_NO, MEM_NO, CARD_TYPE_NO, USE_TIMES) VALUE(?, ?, ?, ?)";
			
			QueryRunner runner = new QueryRunner(TransactionManager.getSource());
			runner.update(sql, card.getCardNo(), card.getMemNo(), card.getCardTypeNo(), 0);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public Card findByCardNo(String cardNo) {
		try {
			String sql = "SELECT * FROM card WHERE CARD_NO=?";
			
			QueryRunner runner = new QueryRunner(TransactionManager.getSource());
			Map<String, Object> queryRes = runner.query(sql, new MapHandler(), cardNo);
			
			if(queryRes == null || queryRes.size() == 0){
				return null;
			}
			
			Card card = new Card();
			card.setCardTypeNo((Integer)queryRes.get("CARD_TYPE_NO"));
			card.setMemNo((Integer)queryRes.get("MEM_NO"));
			card.setCardNo((String)queryRes.get("CARD_NO"));
			card.setUseTimes((Integer) queryRes.get("USE_TIMES"));
			card.setValidTime((Timestamp) queryRes.get("VALID_TIME"));
			
			return card;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
